package fiszkas

import grails.transaction.Transactional

@Transactional
class FiszkaImportService {

    private static final String DELIMITER = "\t"

    def importFromFile(File file) {

        def txt = file.getText()

        return importFromTxt(txt)
    }

    def importFromTxt(txt) {

        def all = Fiszka.list()
        def mapEn = [:]
        def mapPl = [:]
        all.each {
            mapEn[it.english] = it
            mapPl[it.polish] = it
        }

        Fiszka fiszka

        def count = [
                changedPl: 0,
                changedEn: 0,
                added: 0]

        txt.splitEachLine(DELIMITER) { fields ->

            if (fields != null && fields.size() > 0
                    && !fields[0].trim().startsWith("#")) {

                def pl = fields[0]
                def en = fields[1]

                //println "$pl -> $en"

                Fiszka fen = mapEn[en]
                Fiszka fpl = mapPl[pl]

                if (fen != null || fpl != null) {
                    if (fen == null) {
                        fpl.english = en
                        fpl.save()
                        count.changedEn++
                    } else if (fpl == null) {
                        println "${fen.id} ${fen.english} ${fen.polish}->$pl"
                        fen.polish = pl
                        fen.save()
                        count.changedPl++
                    } else {
                        if (fpl.id != fen.id)
                            throw new Exception("istnieja osobne fiszki zarowno dla en i pl: $fpl , $fen")
                    }
                } else {
                    fiszka = Fiszka.createFiszka(
                            polish: fields[0],
                            english: fields[1],
                    )

                    if (fiszka.hasErrors()) {
                        throw new Exception(fiszka.errors.toString())
                    } else {
                        fiszka.save()
                    }
                    count.added++
                }

            }
        }

        println count

        return count
    }
}
